/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.msk.wlhy.service;


import com.msk.base.service.GenerateContractService;
import com.msk.common.core.domain.model.LoginUser;
import com.msk.common.exception.GlobalException;
import com.msk.common.utils.DateUtils;
import com.msk.common.utils.StringUtils;
import com.msk.common.utils.spring.SpringUtils;
import com.msk.sys.domain.Office;
import com.msk.sys.service.CrudService;
import com.msk.sys.utils.DictMskUtils;
import com.msk.wlhy.domain.*;
import com.msk.wlhy.mapper.HtTransportDetailDao;
import com.msk.wlhy.mapper.HtTransportListDao;
import com.msk.wlhy.service.thread.TransportContractService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 作者: zkp
 * @ClassName 类名: HtTransportListService
 * @description 描述:派车单管理Service
 * @date 时间: 2018/06/08
 */
@Service
@Transactional(readOnly = true)
public class HtTransportListService extends CrudService<HtTransportListDao, HtTransportList> {
	@Autowired
	private HtTransportDetailDao htTransportDetailDao;
	@Autowired
	private HtTransportDetailService htTransportDetailService;
	@Autowired
	private HtLogisticsOrderDetailService htLogisticsOrderDetailService;
	@Autowired(required = true)
	private HtDriverFileService htDriverFileService;
	@Autowired(required = true)
	private HtSupplierService htSupplierService;
	@Autowired
	private HtCarFilesService htCarFilesService;
	@Autowired
	private HtLogisticsOrderService htLogisticsOrderService;
	@Autowired
	private HtTransportListDao htTransportListDao;
	@Autowired
	private TransportContractService transportContractService;


	public HtTransportList get(String id) {
		HtTransportList htTransportList = new HtTransportList();
		if(StringUtils.isNotEmpty(id)){
			htTransportList = super.get(id);
			if (htTransportList == null) {
				htTransportList = new HtTransportList();
			}
			HtTransportDetail htTransportDetail = new HtTransportDetail();
			htTransportDetail.setTransportId(id);

			List<HtTransportDetail> list = htTransportDetailDao.findList(htTransportDetail);
			htTransportList.setHtTransportDetailList(list);

			if( !list.isEmpty()){
				String ordId = list.get(0).getOrderDetailId();
				HtLogisticsFrame htLogisticsFrame = htTransportDetailDao.findFrameContract(ordId);
				htTransportList.setHtLogisticsFrame(htLogisticsFrame);
			}
		}
		return htTransportList;
	}

	public List<HtTransportList> findList(HtTransportList htTransportList) {
		return htTransportListDao.findList(htTransportList);
	}

	public List<Map<String,Object>> findHtTransportList(HtTransportList htTransportList) {
		return htTransportListDao.findHtTransportList(htTransportList);
	}

	public Map<String,Object> entryOfWaybill(String id){
		return htTransportListDao.entryOfWaybill(id);
	}

	public List<Map<String,Object>> htTransportCount(HtTransportList htTransportList){
		return htTransportListDao.htTransportCount(htTransportList);
	}

	public HtTransportList selectDispatchOrderById(HtTransportList htTransportList){
		return  htTransportListDao.selectDispatchOrderById(htTransportList);
	}


//	public List<HtTransportList> findPage(HtTransportList htTransportList) {
////		User u = UserUtils.getUser();
//		User u = new User("8dba66ebdd87438390ea255d53454690");
//		//货主及子账号查看运单信息
//		if(u != null && u.getUserIdentity() != null && "2".equalsIgnoreCase(u.getUserIdentity())){
//			htTransportList.setAttstr01(u.getId());
//			htTransportList.setAttstr03("1");
//		}else if(u != null && StringUtils.isNotBlank(u.getMainAccountId()) && "0".equalsIgnoreCase(u.getAccountType()) ){
//			htTransportList.setAttstr01(u.getId());
//			htTransportList.setAttstr03(u.getFatherOfficeId());
//		}
//		return htTransportListDao.findList(htTransportList);
//	}

	@Transactional(readOnly = false)
	public void save(HtTransportList htTransportList) {
		super.save(htTransportList);
	}
	

//	@Transactional(readOnly = false)
//	public HtLogisticsOrderDetail updateOrderDetailInfo(HtTransportList htTransportList,HtLogisticsOrderDetail htLogisticsOrderDetail,String goodsWeight){
//		User user = UserUtils.getUser();
//		String supplierId = "";
//		if("1".equals(user.getUserIdentity())){
//			HtDriverFile htDriverFile = htDriverFileService.getDriverByUserId(user.getId());
//			if(htDriverFile!=null){
//				supplierId = htDriverFile.getId();
//			}
//		}else if("3".equals(user.getUserIdentity())){
//			HtSupplier htSupplier = htSupplierService.getHtSupplierByUserId(user.getId());
//			if(htSupplier!=null){
//				supplierId = htSupplier.getId();
//			}
//		}
//		//如果司机本次拉货重量大于等于货源发布重量则表示订单一次被拉完
//		if(Double.parseDouble(goodsWeight) >= htLogisticsOrderDetail.getGoodsWeight()){
//			if(htLogisticsOrderDetail.getSupplier()==null || "".equals(htLogisticsOrderDetail.getSupplier().getId())) {
//				htLogisticsOrderDetail.setSupplier(new HtSupplier(supplierId));
//			}
//			htLogisticsOrderDetail.setGenerateStatus("1");
//			htLogisticsOrderDetail.setGenerateTime(new Date());
//			htLogisticsOrderDetail.setGoodsStartTime(new Date());
//			htLogisticsOrderDetailService.save(htLogisticsOrderDetail);
//			htTransportList.setOrderDetailId(htLogisticsOrderDetail.getId());
//			return htLogisticsOrderDetail;
//		}else{
//			BigDecimal lastGoodsWeight = new BigDecimal(htLogisticsOrderDetail.getGoodsWeight()).subtract(new BigDecimal(goodsWeight)).setScale(3, RoundingMode.HALF_DOWN);
//			htLogisticsOrderDetail.setGoodsWeight(lastGoodsWeight.doubleValue());
//			htLogisticsOrderDetailService.save(htLogisticsOrderDetail);
//			//生成合同明细
//			HtLogisticsOrderDetail htLogisticsOrderDetail1 = new HtLogisticsOrderDetail();
//			String dateStr =  DateUtils.getDate("yyyyMMdd-");
//			String htCodeDetail = DictUtils.getDictLabel("TYD", "ht_code", "TYD") + "-";
//			//获取当前日期
//			htLogisticsOrderDetail1.setOriginalNumber(htCodeDetail);
//			String originalNumber = htLogisticsOrderDetailService.getOriginalNumber(htLogisticsOrderDetail1 );
//			String originalNumberStr = "";
//			if(null != originalNumber){
//				originalNumber = originalNumber.replace(htCodeDetail,"");
//				//判断今天是否已经有托运单
//				if(originalNumber.startsWith(dateStr)){
//					//有递增+1
//					originalNumber = originalNumber.replace(dateStr,"");
//					Integer originalNumberInt = Integer.parseInt(originalNumber) + 1;
//					originalNumberStr = htCodeDetail+ dateStr+ String.format("%05d", originalNumberInt);
//				}else{
//					//没有生成第一单
//					originalNumberStr = htCodeDetail+dateStr + "00001";
//				}
//			}else{
//				//没有生成第一单
//				originalNumberStr = htCodeDetail+dateStr + "00001";
//			}
//			HtLogisticsOrderDetail htLogisticsOrderDetail2 = new HtLogisticsOrderDetail();
//			BeanUtils.copyProperties(htLogisticsOrderDetail,htLogisticsOrderDetail2);
//			//新增执行单
//			htLogisticsOrderDetail2.setId(null);
//			htLogisticsOrderDetail2.setSupplier(new HtSupplier(supplierId));
//			htLogisticsOrderDetail2.setOriginalNumber(originalNumberStr);
//			htLogisticsOrderDetail2.setGoodsWeight(Double.parseDouble(goodsWeight));
//			htLogisticsOrderDetail2.setGenerateStatus("1");
//			htLogisticsOrderDetail2.setGenerateTime(new Date());
//			htLogisticsOrderDetail2.setGoodsStartTime(new Date());
//			htLogisticsOrderDetailService.save(htLogisticsOrderDetail2);
//			htTransportList.setOrderDetailId(htLogisticsOrderDetail2.getId());
//			//接单异步执行生成平台和司机的合同
//			TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
//				// 在事务提交之后执行的代码块（方法）  此处使用TransactionSynchronizationAdapter，其实在Spring5后直接使用接口也很方便了~
//				@Override
//				public void afterCommit() {
//					GenerateContractService generateContractService = SpringContextHolder.getBean(GenerateContractService.class);
//					new Thread(()->{
//						generateContractService.generateSupplierContract(htLogisticsOrderDetail2.getId());
//					}).start();
//				}
//			});
//			return htLogisticsOrderDetail2;
//		}
//	}


	@Transactional(readOnly = false)
	public void returnhtTransportDetail(HtTransportList htTransportList,HtTransportDetail htTransportDetail) throws Exception {

		htTransportDetail.setStatus("1");//运输中
		htTransportList.setRemarks("");

		htTransportDetail.setCreateDate(new Date());
		Double goodsWeight = htTransportDetail.getGoodsWeight();

		//接收报价
		Double revicePrice = htTransportDetail.getRecivePrice();
		htTransportDetail.setRevicePrice("0");
		htTransportDetail.setGoodsWeight(0.00);
		htTransportDetail.setAllFreight(0.00);
		htTransportDetail.setGoodsTotalPrice(0.00);
		//htTransportDetail.setTaskDescription("");

		htTransportDetailDao.update(htTransportDetail);

		htTransportList.setIsOrders("0");
		htTransportList.setMobileStatus("1");
		htTransportList.setIsEnter("2");
		updateStatus(htTransportList);

		//重置htTransportDetail

		htTransportDetailDao.update(htTransportDetail);
//		materialDetailDao.deleteByTspId(htTransportList.getId());
		dao.update(htTransportList);
		String driverId = "";
		HtDriverFile htDriverFile = new HtDriverFile();
		if(htTransportList != null && StringUtils.isNotBlank(htTransportList.getAttstr01())){
			driverId = htTransportList.getAttstr01();
			htDriverFile = htDriverFileService.get(driverId);
		}

		if(htDriverFile != null){
			htDriverFile.setDriverStatus("1");
			htDriverFileService.updatedriverStatus(htDriverFile);
		}
	//	super.save(htTransportList);
		HtLogisticsOrderDetail orderDetail = htLogisticsOrderDetailService.get(htTransportDetail.getOrderDetailId());
		//重置orderDetail重量
		if(orderDetail!=null && htTransportDetail.getGoodsWeight()!=null){
			orderDetail.setRealGoodsWeight(orderDetail.getRealGoodsWeight() -  goodsWeight);
			if(orderDetail.getRealGoodsWeight() >= orderDetail.getGoodsWeight()){
				orderDetail.setAttstr03("1");
			}
			htLogisticsOrderDetailService.save(orderDetail);
		}

	}

	@Transactional(readOnly = false)
	public void delete(HtTransportList htTransportList) {
		super.delete(htTransportList);
		HtTransportDetail htTransportDetail = new HtTransportDetail();
		htTransportDetail.setTransportId(htTransportList.getId());
		htTransportDetailDao.delete(htTransportDetail);
	}

	@Transactional(readOnly = false)
	public int deleteIds(String id) {
		int result = 0;
		super.delete(new HtTransportList(id));
		HtTransportDetail htTransportDetail = new HtTransportDetail();
		htTransportDetail.setTransportId(id);
		HtDriverFile driver = new HtDriverFile();
		Map<String, Object> map = htTransportDetailService.selectHtTransportDetail(htTransportDetail);
		String orderDetailId = StringUtils.getString(map.get("orderDetailId"));
		HtLogisticsOrderDetail orderDetail = htLogisticsOrderDetailService.get(orderDetailId);
		String attstr03 = StringUtils.getString(map.get("attstr03"));
		if(map != null && StringUtils.isNotBlank(attstr03)){
			String driverId = StringUtils.getString(map.get("attstr03"));
			driver.setId(driverId);
			driver.setDriverStatus("0");//闲置
			htDriverFileService.updatedriverStatus(driver);
		}
		if(orderDetail != null && map.get("goodsWeight") != null){
			double goodsWeight = Double.parseDouble(StringUtils.getString(map.get("goodsWeight")));
			orderDetail.setRealGoodsWeight(orderDetail.getRealGoodsWeight() -  goodsWeight);
			htLogisticsOrderDetailService.save(orderDetail);
		}
		htTransportDetailDao.delete(htTransportDetail);
		result++;
		return result;
	}

	/**
	 * 这里只涉及到对运输单的修改操作
	 * 
	 * @param htTransportList
	 *            void
	 * @throws
	 */
	@Transactional(readOnly = false)
	public void saveDetailData(HtTransportList htTransportList) throws Exception {
		
		
		for (HtTransportDetail htTransportDetail : htTransportList.getHtTransportDetailList()) {
			if (htTransportDetail.getId() == null) {
				continue;
			}
			if (HtLogisticsOrderDetail.DEL_FLAG_NORMAL.equals(htTransportDetail.getDelFlag())) {
				if (!StringUtils.isBlank(htTransportDetail.getId())) {
					this.updateDetailData(htTransportDetail);
				}
			}
		}
		// 执行完成后根据运输单id找到对应的所有订单，根据订单明细反馈的重量和状态回写订单的状态
		/*List<Map<String, Object>> listMap = htLogisticsOrderService.findListByTransportId(htTransportList.getId());
		if (!CollectionUtils.isEmpty(listMap)) {
			for (Map<String, Object> map : listMap) {
				String orderId = map.get("id").toString();
				// minStatusSum是根据运输单查到相应订单后按订单id分组个数*3得到的数字，因为在订单明细中3表示已完成4表示超额完成
				// realStatusSum是根据运输单查到相应订单后按订单id分组算的订单明细状态的求和（其中如果订单明细状态大于4安装3计算），
				// 当这个求和大于等于minStatusSum时说明订单下所有的明细都已完成
				Double minStatusSum = map.get("minStatusSum") == null ? 1 : Double.parseDouble(map.get("minStatusSum").toString());
				Double realStatusSum = map.get("realStatusSum") == null ? 0 : Double.parseDouble(map.get("realStatusSum").toString());
				if (realStatusSum >= minStatusSum) {
					HtLogisticsOrder htLogisticsOrder = htLogisticsOrderService.get(orderId);
					htLogisticsOrder.setStatus("3");
					htLogisticsOrderService.save(htLogisticsOrder);
				}
			}
		}*/
	}

	@Transactional(readOnly = false)
	public void updateDetailData(HtTransportDetail htTransportDetail) throws Exception {
		Double afterGoodsWeight = htTransportDetail.getAfterGoodsWeight() == null ? 0d : htTransportDetail.getAfterGoodsWeight();
		Double beforeGoodsWeight = htTransportDetail.getBeforeGoodsWeight() == null ? 0d : htTransportDetail.getBeforeGoodsWeight();
		Double goodsWeight = 0d;// 货物重量重新计算，防止前台篡改
		if (afterGoodsWeight < beforeGoodsWeight) {
			new GlobalException("拉货后重量必须大于拉货前重量");
		} else {
			goodsWeight = afterGoodsWeight - beforeGoodsWeight;
		}
		if (goodsWeight > 0) {
			Date startDate = htTransportDetail.getStartDate();
			if (startDate == null) {
				htTransportDetail.setStartDate(new Date());
			}
			htTransportDetail.setGoodsWeight(goodsWeight);
			HtTransportDetail oldHtTransportDetail = htTransportDetailService.get(htTransportDetail.getId());
			
			//修改订单明细中的已运重量
			HtLogisticsOrderDetail detail = htLogisticsOrderDetailService.get(htTransportDetail.getOrderDetailId());
			detail.setRealGoodsWeight(htTransportDetail.getGoodsWeight() + (detail.getRealGoodsWeight() == null ? 0d : detail.getRealGoodsWeight())  - (oldHtTransportDetail.getGoodsWeight() == null ? 0d : oldHtTransportDetail.getGoodsWeight()));
			htLogisticsOrderDetailService.save(detail);
			Long count  = htLogisticsOrderService.findCountByOrderId(detail.getOrderId());
			if(count.intValue() == 0){  //未完成量如果为0，则表示该物理合同订单已经完成
				HtLogisticsOrder htLogisticsOrder = htLogisticsOrderService.get(detail.getOrderId());
				htLogisticsOrder.setStatus("3");
				htLogisticsOrderService.save(htLogisticsOrder);
			}
			htTransportDetailService.save(htTransportDetail);
			// 修改完成后需要根据运单明细表中反馈的重量去修改相应的表状态
			// 1修改车辆档案表状态，拉货后修改状态为在途状态
			updateCarFilesData(htTransportDetail.getId());
			// 2根据称重重量反馈到订单明细表中
			// 3根据订单明细中反馈上来的数据修改订单状态
		}
	}

	public void updateCarFilesData(String htTransportDetailId) throws Exception {
		HtCarFiles htCarFilesQuery = new HtCarFiles();
		htCarFilesQuery.setTransportDetailId(htTransportDetailId);
		List<HtCarFiles> htCarFilesList = htCarFilesService.findListByTransportDetailId(htCarFilesQuery);
		HtTransportDetail htTransportDetail= htTransportDetailDao.get(htTransportDetailId);
		String driverId = "";
		HtDriverFile htDriverFile = new HtDriverFile();
		if(htTransportDetail != null && StringUtils.isNotBlank(htTransportDetail.getTransportId())){
			HtTransportList htTransportList = dao.get(htTransportDetail.getTransportId());
			if(htTransportList != null && StringUtils.isNotBlank(htTransportList.getAttstr01())){
				driverId = htTransportList.getAttstr01();
				htDriverFile = htDriverFileService.get(driverId);
			}
		}

		if (CollectionUtils.isEmpty(htCarFilesList)) {
			new GlobalException("未找到相应的车辆信息，请联系管理员");
		} else if (htCarFilesList.size() == 1) {
			HtCarFiles htCarFiles = htCarFilesList.get(0);
			String status = htCarFiles.getStatus();
			if (status.equals("1")) {
				htCarFiles.setStatus("2");// 运输中
			}
			if(htDriverFile != null&& "0".equalsIgnoreCase(htDriverFile.getDriverStatus())){
				htDriverFile.setDriverStatus("2");
				htDriverFileService.updatedriverStatus(htDriverFile);
			}
			htCarFilesService.save(htCarFiles);

			//修改对应车牌号的所有车辆
			HtCarFiles carFiles = new HtCarFiles();
			carFiles.setCarNumber(htCarFiles.getCarNumber());
			List<HtCarFiles> list = htCarFilesService.findListAll(carFiles);
			for (HtCarFiles htCarFiles2 : list) {
				htCarFiles2.setStatus("2");
				htCarFilesService.save(htCarFiles2);
			}
		} else if (htCarFilesList.size() > 1) {
			new GlobalException("找到多条车辆信息，请联系管理员");
		}
	}

	/**
	 * @description findCurrentList
	 * @date 2018-7-3
	 * @author chuming
	 * @param htTransportList
	 * @return
	 */
	public List<HtTransportList> findCurrentList(HtTransportList htTransportList) {
		return dao.findCurrentList(htTransportList);
	}

	/**
	 * 获取各个部门的运输单数量信息
	 * @description getCountGroupbyOffice
	 * @date 2018-7-10
	 * @author chuming
	 * @return
	 */
	public List<Map<String, Object>> getCountGroupbyOffice(HtTransportList htTransportList) {
		//htTransportList.getSqlMap().put("dsf", BaseService.dataScopeFilter(htTransportList.getCurrentUser(), "o3", "u"));
		return dao.getCountGroupbyOffice(htTransportList);
	}

	/**
	 * @description updateDelFlag
	 * @date 2018-8-2
	 * @author chuming
	 * @param htTransportList
	 */
	@Transactional(readOnly = false)
	public void updateDelFlag(HtTransportList htTransportList) {
		dao.updateDelFlag(htTransportList);
	}
	
	/**
	 * @description getOrderList
	 * @date 2018-8-13
	 * @author chuming
	 * @return
	 */
	public List<HtTransportList> getOrderList(String phone){
		return dao.getOrderList(phone);
	}
	
	/**
	 * @description getMyOrderList
	 * @date 2018-8-13
	 * @author chuming
	 * @return
	 */
	public List<HtTransportList> getMyOrderList(HtTransportList htTransportList){
		return dao.getMyOrderList(htTransportList);
	}
	/**
	 * @description updateDelFlag
	 * @date 2018-8-2
	 * @author chuming
	 * @param htTransportList
	 */
	@Transactional(readOnly = false)
	public void updateStatus(HtTransportList htTransportList){
		dao.updateStatus(htTransportList);
	}


	public int findInfoById (String id){
		return dao.findInfoById(id);
	}

	public Map<String,Object> getIsLastOrder(String transportId,double thisGoodsWeight){
		Map<String,Object> map = new HashMap<>();
		HtTransportList transportList = this.get(transportId);
		double sunFreightPrice = 0;
		double sumAllRecivePrice = 0;
		double allFreightPrice = 0;
		double allRecivePrice = 0;
		double remainingAllPrice = 0;
		double remainingFreight = 0;
		double remainingWeight = 0;
		double oldFreight = 0;
		double oldPrice = 0;
		BigDecimal freight = null;
		BigDecimal allFreight = null;
		BigDecimal price = null;
		BigDecimal allPrice = null;
		double distance = 0;
		String priceType ="0";//报价方式0单价1总价
		String priceWay = "1";
		if(transportList!=null ) {
			priceType = transportList.getPriceType();
			priceWay = transportList.getPriceWay();
			allFreightPrice = transportList.getAllFreightPrice();
			allRecivePrice = transportList.getAllRecivePrice();
			double goodsWeight = transportList.getGoodsWeight();
			double realWeight = transportList.getRealGoodsWeight();
			if(goodsWeight > realWeight)
				remainingWeight = goodsWeight - realWeight;

			List<HtTransportDetail> transportDetailList = transportList.getHtTransportDetailList();
			HtTransportDetail transportDetail = transportDetailList ==null ? null : transportDetailList.get(0);
			if(transportDetail!=null && transportDetail.getOrderDetailId()!=null) {
				oldFreight = transportDetail.getFreight();
				oldPrice = transportDetail.getPrice();
				distance = Double.parseDouble(transportDetail.getDistance()) ;
				transportDetail = htTransportDetailService.getAllFreightPrice(transportDetail);
				sunFreightPrice = transportDetail.getSumAllFreight();
				sumAllRecivePrice = transportDetail.getSumAllRecivePrice();
				if(allFreightPrice> sunFreightPrice)
					remainingFreight = allFreightPrice - sunFreightPrice;
				if(allRecivePrice > sumAllRecivePrice)
					remainingAllPrice = allRecivePrice - sumAllRecivePrice;
			}
		}
		//本车拉货重量>=剩余重量为最后一车
		if(thisGoodsWeight >= remainingWeight && "1".equals(priceType)){
			freight =  new BigDecimal(remainingFreight/(thisGoodsWeight == 0 ? 1 : thisGoodsWeight)/(distance == 0 ? 1 : distance)).setScale(8, RoundingMode.HALF_DOWN);
			allFreight =  new BigDecimal(remainingFreight).setScale(0, RoundingMode.HALF_DOWN);

			price = new BigDecimal(remainingAllPrice/(thisGoodsWeight == 0 ? 1 : thisGoodsWeight)/(distance == 0 ? 1 : distance)).setScale(8, RoundingMode.HALF_DOWN);
			allPrice = new BigDecimal(remainingAllPrice).setScale(0, RoundingMode.HALF_DOWN);
		}else{
			freight =  new BigDecimal(oldFreight).setScale(8, RoundingMode.HALF_DOWN);
			if("3".equalsIgnoreCase(priceWay)){
				//元/吨
				allFreight =  new BigDecimal(oldFreight * thisGoodsWeight).setScale(0, RoundingMode.HALF_DOWN);
			}else{
				allFreight =  new BigDecimal(oldFreight * thisGoodsWeight * distance).setScale(0, RoundingMode.HALF_DOWN);
			}

			price = new BigDecimal(oldPrice).setScale(8, RoundingMode.HALF_DOWN);
			allPrice = new BigDecimal(oldPrice * thisGoodsWeight * distance).setScale(0, RoundingMode.HALF_DOWN);
		}
		map.put("freight",freight);
		map.put("allFreight",allFreight);
		map.put("price",price);
		map.put("allPrice",allPrice);
		return map;
	}

	/**
	 * 查询已派车数量
	 * @param id
	 * @return
	 */
	public int checkCarCount(String id){
		return  dao.checkCarCount(id);
	}

	@Transactional(readOnly = false)
	public HtLogisticsOrderDetail updateOrderDetailInfo(HtTransportList htTransportList, HtLogisticsOrderDetail htLogisticsOrderDetail, String goodsWeight, LoginUser loginUser){
		String supplierId = "";
		if("1".equals(loginUser.getLoginObject())){
			HtDriverFile htDriverFile = htDriverFileService.getDriverByUserId(loginUser.getLoginId());
			if(htDriverFile!=null){
				supplierId = htDriverFile.getId();
			}
		}else if("3".equals(loginUser.getLoginObject())){
			HtSupplier htSupplier = htSupplierService.getHtSupplierByUserId(loginUser.getLoginId());
			if(htSupplier!=null){
				supplierId = htSupplier.getId();
			}
		}
		//如果司机本次拉货重量大于等于货源发布重量则表示订单一次被拉完
		if(Double.parseDouble(goodsWeight) >= htLogisticsOrderDetail.getGoodsWeight()){
			if(htLogisticsOrderDetail.getSupplier()==null || "".equals(htLogisticsOrderDetail.getSupplier().getId())) {
				htLogisticsOrderDetail.setSupplier(new HtSupplier(supplierId));
			}
			htLogisticsOrderDetail.setGenerateStatus("1");
			htLogisticsOrderDetail.setGenerateTime(new Date());
			htLogisticsOrderDetail.setGoodsStartTime(new Date());
			htLogisticsOrderDetailService.save(htLogisticsOrderDetail);
			htTransportList.setOrderDetailId(htLogisticsOrderDetail.getId());
			return htLogisticsOrderDetail;
		}else{
			BigDecimal lastGoodsWeight = new BigDecimal(htLogisticsOrderDetail.getGoodsWeight()).subtract(new BigDecimal(goodsWeight)).setScale(3, RoundingMode.HALF_DOWN);
			htLogisticsOrderDetail.setGoodsWeight(lastGoodsWeight.doubleValue());
			htLogisticsOrderDetailService.save(htLogisticsOrderDetail);
			//生成合同明细
			HtLogisticsOrderDetail htLogisticsOrderDetail1 = new HtLogisticsOrderDetail();
			String dateStr =  DateUtils.getDate("yyyyMMdd-");
			String htCodeDetail = DictMskUtils.getDictLabel("TYD","ht_code","") + "-";
			//获取当前日期
			htLogisticsOrderDetail1.setOriginalNumber(htCodeDetail);
			String originalNumber = htLogisticsOrderDetailService.getOriginalNumber(htLogisticsOrderDetail1 );
			String originalNumberStr = "";
			if(null != originalNumber){
				originalNumber = originalNumber.replace(htCodeDetail,"");
				//判断今天是否已经有托运单
				if(originalNumber.startsWith(dateStr)){
					//有递增+1
					originalNumber = originalNumber.replace(dateStr,"");
					Integer originalNumberInt = Integer.parseInt(originalNumber) + 1;
					originalNumberStr = htCodeDetail+ dateStr+ String.format("%05d", originalNumberInt);
				}else{
					//没有生成第一单
					originalNumberStr = htCodeDetail+dateStr + "00001";
				}
			}else{
				//没有生成第一单
				originalNumberStr = htCodeDetail+dateStr + "00001";
			}
			HtLogisticsOrderDetail htLogisticsOrderDetail2 = new HtLogisticsOrderDetail();
			BeanUtils.copyProperties(htLogisticsOrderDetail,htLogisticsOrderDetail2);
			//新增执行单
			htLogisticsOrderDetail2.setId(null);
			htLogisticsOrderDetail2.setSupplier(new HtSupplier(supplierId));
			htLogisticsOrderDetail2.setOriginalNumber(originalNumberStr);
			htLogisticsOrderDetail2.setGoodsWeight(Double.parseDouble(goodsWeight));
			htLogisticsOrderDetail2.setGenerateStatus("1");
			htLogisticsOrderDetail2.setGenerateTime(new Date());
			htLogisticsOrderDetail2.setGoodsStartTime(new Date());
			htLogisticsOrderDetailService.save(htLogisticsOrderDetail2);
			htTransportList.setOrderDetailId(htLogisticsOrderDetail2.getId());
			//接单异步执行生成平台和司机的合同
			TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
				// 在事务提交之后执行的代码块（方法）  此处使用TransactionSynchronizationAdapter，其实在Spring5后直接使用接口也很方便了~
				@Override
				public void afterCommit() {
					GenerateContractService generateContractService = SpringUtils.getBean(GenerateContractService.class);
					new Thread(()->{
						generateContractService.generateSupplierContract(htLogisticsOrderDetail2.getId());
					}).start();
				}
			});
			return htLogisticsOrderDetail2;
		}
	}
	
	

	@Transactional(readOnly = false)
	public void saveDataNew(HtTransportList htTransportList) throws Exception {
		super.save(htTransportList);
		Date nowTime = new Date();
		HtTransportDetail htTransportDetail = htTransportList.getHtTransportDetail();
		String goodsName = htTransportDetail.getGoodsName();
		String startPlace = htTransportDetail.getStartPlace();

		htTransportDetail.setTransportId(htTransportList.getId());
		//htTransportDetail.setOrderDetailId(htTransportList.getOrderDetailId());

		if (htTransportDetail.DEL_FLAG_NORMAL.equals(htTransportDetail.getDelFlag())) {
			if(htTransportDetail.getGasolineBalance()==null){
				htTransportDetail.setGasolineBalance(0.0);
			}
			htTransportDetail.setCreateBy(htTransportList.getCreateBy());
			htTransportDetail.setCompany(htTransportList.getCompany());
			htTransportDetail.setOffice(htTransportList.getOffice());
			htTransportDetail.setRemarks(htTransportList.getRemarks());
			htTransportDetail.setVersion(htTransportList.getVersion());
			htTransportDetail.setOrderNo(htTransportList.getDispatchCarNumber());
			htTransportDetail.setRevicePrice(String.valueOf(htTransportDetail.getAllFreight()));
			htTransportDetail.setStatus("1");//运输中
			//	htTransportDetail.setStartDate(nowTime);//发货时间

			HtLogisticsOrderDetail orderDetail = htLogisticsOrderDetailService.get(htTransportDetail.getOrderDetailId());
			//设置车辆起始经纬度坐标
			htTransportDetail.setStartCoordinate(orderDetail.getStartCoordinate());
			htTransportDetail.setEndCoordinate(orderDetail.getEndCoordinate());
			htTransportDetailService.save(htTransportDetail);
			
			if(orderDetail!=null && htTransportDetail.getGoodsWeight()!=null){
				orderDetail.setRealGoodsWeight(htTransportDetail.getGoodsWeight() + (orderDetail.getRealGoodsWeight() == null ? 0d : orderDetail.getRealGoodsWeight()));
				if(orderDetail.getRealGoodsWeight() >= orderDetail.getGoodsWeight()){
					orderDetail.setAttstr03("2");
				}
				htLogisticsOrderDetailService.save(orderDetail);
			}
		} else {
			htTransportDetailDao.delete(htTransportDetail);
		}
			
		//开启线程，异步生成pdf片段
		final Map<String, Object> map = new HashMap<>();
		map.put("goodsName", goodsName);
		map.put("startPlace", startPlace);
		map.put("endPlace", htTransportList.getPlace());
		Date d1 = htTransportList.getDispatchTime();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		if(d1!=null)
			map.put("startDate", sdf.format(d1));

		Date d2 = htTransportList.getEndDate();
		if(d2!=null)
			map.put("endDate", sdf.format(d2));

		map.put("dat", sdf.format(nowTime));

		map.put("comsignment", htTransportList.getCustomerName());
		map.put("comsignmentLegal", StringUtils.isNull(htTransportList.getCreateBy()) ? "dddc3d5969014e298cb455e8f862eefd" : htTransportList.getCreateBy().getName());

		Office office = htTransportList.getCompany();
		if (office!=null){
			map.put("carriage", office.getName());
			map.put("carriageLegal", office.getMaster());
		}
	}

	@Transactional(readOnly = false)
	public void saveWayBillData(HtTransportList htTransportList) throws Exception {
		super.save(htTransportList);
		String goodsName= "", startPlace="";
		Date nowTime = new Date();
		List<HtTransportDetail> list = htTransportList.getHtTransportDetailList();//运输单明细信息
		for (int i=0, ln=list.size(); i<ln; i++ ) {
			if (htTransportList.getId() == null) {
				continue;
			}
			HtTransportDetail htTransportDetail = list.get(i);
			if(i==0){
				goodsName = htTransportDetail.getGoodsName();
				startPlace = htTransportDetail.getStartPlace();
			}

			htTransportDetail.setTransportId(htTransportList.getId());

			if (htTransportDetail.DEL_FLAG_NORMAL.equals(htTransportDetail.getDelFlag())) {
				if(htTransportDetail.getGasolineBalance()==null){
					htTransportDetail.setGasolineBalance(0.0);
				}
				htTransportDetail.setCompany(htTransportList.getCompany());
				htTransportDetail.setOffice(htTransportList.getOffice());
				htTransportDetail.setRemarks(htTransportList.getRemarks());
				htTransportDetail.setStatus("1");//运输中
				//	htTransportDetail.setStartDate(nowTime);//发货时间
				htTransportDetailService.save(htTransportDetail);

				HtLogisticsOrderDetail orderDetail = htLogisticsOrderDetailService.get(htTransportDetail.getOrderDetailId());
				if(orderDetail!=null && htTransportDetail.getGoodsWeight()!=null){
					orderDetail.setRealGoodsWeight(htTransportDetail.getGoodsWeight() + (orderDetail.getRealGoodsWeight() == null ? 0d : orderDetail.getRealGoodsWeight()));
					if(orderDetail.getRealGoodsWeight() >= orderDetail.getGoodsWeight()){
						orderDetail.setAttstr03("2");
					}
					htLogisticsOrderDetailService.save(orderDetail);
				}
			} else {
				htTransportDetailDao.delete(htTransportDetail);
			}

		}
		//开启线程，异步生成pdf片段
		final Map<String, Object> map = new HashMap<>();
		map.put("goodsName", goodsName);
		map.put("startPlace", startPlace);
		map.put("endPlace", htTransportList.getPlace());
		Date d1 = htTransportList.getDispatchTime();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		if(d1!=null)
			map.put("startDate", sdf.format(d1));

		Date d2 = htTransportList.getEndDate();
		if(d2!=null)
			map.put("endDate", sdf.format(d2));

		map.put("dat", sdf.format(nowTime));

		map.put("comsignment", htTransportList.getCustomerName());
		map.put("comsignmentLegal", htTransportList.getCreateBy().getName());

		Office office = htTransportList.getCompany();
		if (office!=null){
			map.put("carriage", office.getName());
			map.put("carriageLegal", office.getMaster());
		}

		//异步生成合同
		final String titl =goodsName;
		final String id = htTransportList.getId();
		new Thread( () ->
				transportContractService.genFile(id, titl, map)
		).start();
	}
}